package com.wugh.fast.kernel.util;

import com.wugh.fast.kernel.core.exception.FastGlobalException;
import com.wugh.fast.kernel.util.dto.AnalysisResultOfBase64DTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tika.mime.MimeType;
import org.apache.tika.mime.MimeTypeException;
import org.apache.tika.mime.MimeTypes;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Base64位工具
 *
 * @author 吴冠辉
 * @date 2018/6/28 18:38
 */
@Slf4j
public class Base64Utils {
    /**
     * base64位的头部文件识别文件
     */
    public static final Pattern BASE64_PATTERN = Pattern.compile("^data:(\\w+/\\w+);base64,");

    public static final MimeTypes MIME_TYPES_MAP;
    public static final MimeType DEFAULT_MIME_TYPE;

    static {
        MIME_TYPES_MAP = MimeTypes.getDefaultMimeTypes();
        try {
            DEFAULT_MIME_TYPE = MIME_TYPES_MAP.getRegisteredMimeType("application/octet-stream");
        } catch (MimeTypeException e) {
            log.error("初始化默认的类型失败");
            System.exit(1);
            throw new RuntimeException(e);
        }
    }

    private Base64Utils() {

    }

    public static AnalysisResultOfBase64DTO parse(String base64Data) {
        Matcher matcher = BASE64_PATTERN.matcher(base64Data);
        if (!matcher.find()) {
            throw new FastGlobalException("无效的Base64数据,转化失败");
        }

        String group = matcher.group();
        String contentType = BASE64_PATTERN.matcher(group).replaceFirst("$1");
        String data = StringUtils.replaceAll(matcher.replaceFirst(""), "\n", "");
        data = StringUtils.replaceAll(data, "\r", "");
        byte[] buffer = org.springframework.util.Base64Utils.decodeFromString(data);
        MimeType registeredMimeType;
        try {
            registeredMimeType = MIME_TYPES_MAP.getRegisteredMimeType(contentType);
        } catch (MimeTypeException e) {
            //无法找到对应的类型时,取字节流
            registeredMimeType = DEFAULT_MIME_TYPE;
        }
        String extension = registeredMimeType.getExtension();
        //去除后缀的.
        extension = extension.startsWith(".") ? extension.substring(1) : extension;
        return new AnalysisResultOfBase64DTO()
                .setBytes(buffer)
                .setContentType(contentType)
                .setData(data)
                .setExtension(extension)
                .setSize((long) buffer.length);
    }
}
